<template>
  <div style="width: 100%">
    <el-collapse v-model="activeName">
      <el-collapse-item name="1" title="基本信息">
        <el-form :disabled="dialogType==='view'" ref="form" :model="formData" :rules="rules"
                 size="small" label-width="110px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="nameCn">
                <el-input v-model="formData.nameCn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码标识" prop="columnName">
                <el-input :disabled="dialogType!=='add'" v-model="formData.columnName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="属性分类" prop="attributeTypeId">
                <el-select style="width: 99%" v-model="formData.attributeTypeId"
                           @change="setAttributeType">
                  <template v-for="item in attributeTypeList">
                    <el-option :label="item.nameCn" :key="item.oid" :value="item.oid"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="属性值" prop="associatedDataType"
                            v-if="attributeObj&&['enum'].includes(attributeObj.name)">
                <el-select style="width: 99%" v-model="formData.associatedDataType"
                           @change="(val)=>enumChange(val,true)">
                  <template v-for="{nameCn,oid} in enumList">
                    <el-option :label="nameCn" :key="oid" :value="oid"></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="属性值" prop="associatedDataType"
                            v-if="attributeObj&&['entity_model'].includes(attributeObj.name)">
                <el-select-tree :value.sync="formData.associatedDataType"
                                :options="parentIdList"></el-select-tree>
              </el-form-item>
               <el-form-item label="属性值" prop="associatedDataType"
                            v-if="attributeObj&& (attributeObj['name'] === 'file')">
                  <el-select style="width: 99%" v-model="formData.associatedDataType">
                    <template v-for="{name,value} in fileList">
                    <el-option :label="name" :key="value" :value="value"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-show="false" v-if="attributeObj&&['decimal','string','number'].includes(attributeObj.columnType)">
            <el-col :span="12">
              <el-form-item label="长度">
                <el-input-number style="width: 100%" :min="1" :max="attributeObj.length"
                                 :value="formData.length = attributeObj.length"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="attributeObj&&attributeObj.columnType==='decimal'">
              <el-form-item label="精度">
                <el-input-number style="width: 100%" :min="0" :max="attributeObj.accuracy"
                                 :value="formData.accuracy=attributeObj.accuracy"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="英文名称" prop="nameEn">
                <el-input v-model="formData.nameEn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="属性类型">
                <el-select disabled style="width: 99%" v-model="formData.attributeType">
                  <template v-for="item in columnTypeList">
                    <el-option :label="item.name" :value="item.type"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文描述">
                <el-input v-model="formData.describeEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="中文描述" prop="describeCn">
                <el-input v-model="formData.describeCn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否必填" prop="required">
                <el-radio-group v-model="formData.required">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认值">
                <el-select v-if="attributeObj&&['enum'].includes(attributeObj.name)"
                           v-model="formData.columnDefault">
                  <template v-for="item in enumValueList">
                    <el-option :value="item.value" :label="item.name"></el-option>
                  </template>
                </el-select>
                <el-input v-else v-model="formData.columnDefault"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="唯一值">
                <el-radio-group v-model="formData.sole">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择类型">
                <el-radio-group v-model="formData.choiceType">
                  <el-radio :label="1">单选</el-radio>
                  <el-radio :label="2">多选</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="单位组">
                <el-select clearable style="width: 100%" v-model="formData.unitGroup" @change="getUnitData">
                  <template v-for="{oid,nameCn} in unitGroupData">
                    <el-option :value="oid" :label="nameCn"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认单位">
                <el-select clearable style="width: 100%" v-model="formData.unit">
                  <template v-for="{name,oid} in unitData">
                    <el-option :value="oid" :label="name"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="密级" prop="secret">
                <el-select style="width: 100%" v-model="formData.secret">
                  <template v-for="{name,value} in secretData">
                    <el-option :label="name" :value="value"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否动态属性" prop="dynamicFlag">
                <el-select style="width: 100%" v-model="formData.dynamicFlag">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <div class="md-component-btns">
      <el-button size="medium" type="primary" v-if="dialogType==='view'"
                 @click="()=>{$emit('viewToEdit'),dialogType='edit'}">编辑
      </el-button>
      <el-button size="medium" type="primary" v-if="dialogType!=='view'" @click="save">保存</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>
  </div>
</template>

<script>
import * as attribute from "@/api/modulManage/attribute"
import * as common from "@/api/common";
import {request} from "axios";
import ElSelectTree from "@/components/el-select-tree.vue";
import * as api from "@/api/modulManage/entity";
import {getColumnType} from "@/api/modulManage/attributeClassify";

export default {
  name: "PropertiesDefinedTemp",
  components: {ElSelectTree},
  inject: ["EnumManageOption"],
  data() {
    return {
      activeName: ["1", "2"],
      formData: {
        nameCn: "",
        nameEn: "",
        attributeType: "",
        columnName: "",
        describeEn: "",
        describeCn: "",
        required: 0,
        columnDefault: "",
        unitGroup: "",
        unit: "",
        attributeTypeId: "",
        secret: "",
        dynamicFlag: "",
        length: 1,
        accuracy: 0,
        associatedDataType: "",
        sole: 0,
        choiceType: 1
      },
      baseRules: {
        nameCn: [{required: true, message: "请输入中文名称", trigger: "blur"}],
        nameEn: [
          {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确英文名称'}
        ],
        columnName: [
          {required: true, message: "请输入编码标识", trigger: "blur"},
          {pattern: '^[a-z][a-z0-9_]{1,29}$', message: '请输入正确编码标识'}
        ],
        attributeTypeId: [{required: true, message: "请选择属性分类", trigger: "change"}],
        describeCn: [{required: true, message: "请输入中文描述", trigger: "blur"}],
        required: [{required: true, message: "请选择是否必填", trigger: "change"}],
        dynamicFlag: [{required: true, message: "请选择是否动态属性", trigger: "change"}],
        secret: [{required: true, message: "请选择密级", trigger: "change"}],
      },
      rules_1: {
        associatedDataType: [{required: true, message: "请选择属性值", trigger: "change"}],
      },
      rules_2: {
        associatedDataType: [{required: true, message: "请选择属性值", trigger: "change"}],
      },

      columnTypeList: [],
      attributeTypeList: [],
      propertiesSelection: [],
      dialogType: "add",

      unitGroupData: [],
      unitData: [],
      secretData: [],

      enumList: [],
      fileList: [],
      parentIdList: [],

      enumValueList: [],
    }
  },
  computed: {
    attributeObj() {
      if (this.attributeTypeList && this.attributeTypeList.length > 0) {
        let ids = this.attributeTypeList.map(i => i.oid);
        let index = ids.indexOf(this.formData.attributeTypeId);
        console.log('this.attributeTypeList[index]',this.attributeTypeList[index])
        return this.attributeTypeList[index];
      }
      return false;
    },
    rules() {
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      if (this.attributeObj && ['enum', 'entity_model'].includes(this.attributeObj.name)) {
        // this.formData.associatedDataType = ""
        return {...this.baseRules, ...this.rules_1}
      }
      return this.baseRules;
    }
  },
  methods: {
    save() {
      let method = this.dialogType === "add" ? "addAttribute" : "updateAttribute";
      this.$refs["form"].validate(f => {
        if (f) {
          attribute[method](this.formData).then((res) => {
            this.$emit("addToList", [res.data.data]);
            this.$emit('refresh');
            this.$emit('removeThisTabs');
          })
        }
      })
    },

    resetDialog() {
      this.formData = {
        nameCn: "",
        nameEn: "",
        attributeType: "",
        typeName: "",
        columnName: "",
        describeEn: "",
        describeCn: "",
        required: "",
        columnDefault: "",
        unitGroup: "",
        unit: "",
        attributeTypeId: "",
        codeTypeId: "",
        secret: "",
        dynamicFlag: "",
        length: 1,
        accuracy: 0,
      }
    },
    enumChange(val, defaultVal) {
      let obj = this.enumList.filter(i => i.oid === val)[0];
      if (obj && obj.name) {
        common.getDic(obj.name).then(res => {
          this.enumValueList = res.data.data;
          let def = res.data.data.filter(i => i.isDefault === 1);
          if (def && def[0] && defaultVal) {
            this.formData.columnDefault = def[0].value;
          }
        })
      }
    },
    getFileType() {
      common.getDic("file_type").then(res => {
        this.fileList = res.data.data;
      })
    },
    setAttributeType(v) {
      console.log('vvvvvvvvvvvvvvvvvv',v)
      console.log('vvvvvvvvvvvvthis.attributeTypeListvvvvvv',this.attributeTypeList)
      this.attributeTypeList.forEach(item => {
        if (item.oid === v) {
          this.formData.attributeType = item.columnType;
      console.log('item.columnType',item.columnType)
      console.log('this.formData.attributeType',this.formData.attributeType)

          if(item.name === 'file'){
            this.getFileType()
          }
        }
      })
    },
    getAttributeType() {
      attribute.getAttribute({state: 1}).then(res => {
        this.attributeTypeList = res.data.data;
      })
    },
    getColumnType() {
      getColumnType().then(res => {
        this.columnTypeList = res.data.data;
      })
    },

    details(row) {
      attribute.getDetail({oid: row.oid}).then(res => {
        for (const key in res.data.data) {
          this.$set(this.formData, key, res.data.data[key])
        }

        this.setAttributeType(this.formData.attributeTypeId);
        if (this.attributeObj && ['enum'].includes(this.attributeObj.name)) {
          this.enumChange(this.formData.associatedDataType)
        }
      })
    },
    getUnitGroupData() {
      common.getUnitGroup({state: 1}).then(res => {
        this.unitGroupData = res.data.data;
      })
    },
    getUnitData(oid) {
      this.formData.unit = "";
      if (!oid) {
        return;
      }
      common.getUnit({oid}).then(res => {
        this.unitData = res.data.data;
        let def = this.unitData.filter(i => i.defaultFlag === 1)
        if (def && def[0]) {
          this.formData.unit = def[0].oid;
        }
      })
    },
    getSecret() {
      common.getDic("secret").then(res => {
        this.secretData = res.data.data;
      })
    },

    edit(row) {
      this.dialogType = "edit";
      this.details(row);
    },

    view(row) {
      this.dialogType = "view";
      this.details(row);
    },

    open() {
      this.dialogType = "add";
    },
    getEnumList() {
      request({url: "/api/manager-api/mx-code-type/list", method: "get"}).then(res => {
        this.enumList = res.data.data;
      })
    },
    getEntityList() {
      api.getEntity().then(res => {
        this.parentIdList = res.data.data;
      })
    },
  },
  mounted() {
    this.getEntityList();
    this.getAttributeType();
    this.getUnitGroupData();
    this.getSecret();
    this.getEnumList();
    this.getColumnType();
  },
  watch: {
    "formData.unitGroup": {
      handler(v) {
        if (v) {
          common.getUnit({oid: v}).then(res => {
            this.unitData = res.data.data;
          })
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style scoped>

</style>
